package servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.pageDAO;
import dao.studentDAO;
import entity.PageConfig;
import entity.student;
import entity.usePage;


public class pageServlet extends HttpServlet {
	
	
	private static final long serialVersionUID = 1L;
       
   
    public pageServlet() {
        super();
        
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String method = request.getParameter("method");
		if(method.equals("first")){
			changePage(request, response);
			//response.sendRedirect("showStudent.jsp");
			request.getRequestDispatcher("showStudent.jsp").forward(request, response);
		}
		if(method.equals("next")){
			changePage(request, response);
			request.getRequestDispatcher("showStudent.jsp").forward(request, response);
		}
		if(method.equals("prev")){
			changePage(request, response);
			request.getRequestDispatcher("showStudent.jsp").forward(request, response);
		}
		if(method.equals("last")){
			changePage(request, response);
			request.getRequestDispatcher("showStudent.jsp").forward(request, response);
		}
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	protected void changePage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		studentDAO studentdao = new studentDAO();
		List<student> list = studentdao.getAllStudents();
		int recordCount = list.size();
		
		usePage p = new usePage();
		PageConfig pc = new PageConfig();
		int currentPage = Integer.parseInt(request.getParameter("currentPage"));
		int pageCount = pc.getPageCount(recordCount,pc.getPageSize());
		
		
		if(currentPage<1){
			request.getRequestDispatcher("pagefail2.jsp").forward(request, response);
		}
		
		if(currentPage>4){
			request.getRequestDispatcher("pagefail.jsp").forward(request, response);
		}
		
		
		pc.setCurrentPage(currentPage);
		pc.setRecordCount(recordCount);
		pc.setPageCount(pageCount);
		
		p.setCurrentPage(currentPage);
		p.setPageSize(3);

		//pc=new PageConfig(currentPage,3,pageCount,recordCount);
//		System.out.println(currentPage);
//		System.out.println((pc.getCurrentPage()-1)*pc.getPageSize());
//		System.out.println(pc.getPageSize());
		
		request.setAttribute("page", p);
		request.setAttribute("page2", pc);
	}
}
